package utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

public class DBUtil {
	private static Connection con;
	private static DataSource ds;
	public static Connection getConnection(){
		try {
			con = DBUtil.ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
	}

	public static void setDataSource(DataSource ds) {
		DBUtil.ds = ds;
	}


	
	
	public static void close(Connection con, PreparedStatement pst, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pst != null) {
				pst.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	@SuppressWarnings("unused")
	private static BasicDataSource dbs;
	
	private final static String className = "oracle.jdbc.OracleDriver";
	private final static String url = "jdbc:oracle:thin:@ZHA-ITA092-W7:1522:orcl";
	private final static String username = "evan";
	private final static String password = "123";
	private static BasicDataSource bds;
	
	public static void setDBCPBds(){
		System.out.println("init....DBCPdatasource...");
		bds = new BasicDataSource();
		bds.setDriverClassName(className);
		bds.setUrl(url);
		bds.setUsername(username);
		bds.setPassword(password);
		bds.setMaxActive(10);
		DBUtil.ds = bds;
	}
}






class DBUtilTest {
	
	private static final String className = "oracle.jdbc.OracleDriver";
	private static final String url = "jdbc:oracle:thin:@ZHA-ITA092-w7:1522:orcl";
	private static final String password = "123";
	private static final String username = "evan";
	private static BasicDataSource ds;
	// 线程安全的重量级对象 单例模式
	static {
		ds = new BasicDataSource();
		ds.setUrl(url);
		ds.setDriverClassName(className);
		ds.setUsername(username);
		ds.setPassword(password);
		ds.setMaxActive(5);
	}

	public static Connection createConnection() {
		Connection con = null;
		try {
			Class.forName(className);
			con = DriverManager.getConnection(url, username, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return con;
	}

	public static Connection createConnectionWithDataSource() {
		Connection connection = null;
		try {
			connection = ds.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return connection;
	}

	public static void close(Connection con, PreparedStatement pst, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
			if (pst != null) {
				pst.close();
			}
			if (con != null) {
				con.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}
